﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using PiscoSourPersistencia;
using PiscoSourDominio;
using System.Messaging;

namespace PiscoSourRESTServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Ordenes" in code, svc and config file together.
    public class Ordenes : IOrdenes
    {
        private OrdenDAO dao = new OrdenDAO();

        public string IngresarOrdenCola(Orden objOrden)
        {
            string strrutaCola = @".\private$\PISCOSOUR";

            try
            {
                if (!MessageQueue.Exists(strrutaCola))
                {
                    MessageQueue.Create(strrutaCola);
                }

                MessageQueue mqcola = new MessageQueue(strrutaCola);
                Message msjmessage = new Message();
                msjmessage.Label = "orden " + DateTime.Now.ToString("ddMMyyyy_hhmmss");
                msjmessage.Body = objOrden;
                mqcola.Send(msjmessage);
                return "OK";
            }
            catch (Exception ex)
            {
                return "ERROR";
            }
        }

        public string TomarOrdenCola()
        {
            string strrutaCola = @".\private$\PISCOSOUR";

            try
            {
                if (!MessageQueue.Exists(strrutaCola))
                {
                    MessageQueue.Create(strrutaCola);
                }

                MessageQueue mqcola = new MessageQueue(strrutaCola);
                mqcola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Orden) });
                Message msjmessage = null;
                Orden objOrden = null;

                foreach (Message msg in mqcola.GetAllMessages())
                {
                    msjmessage = mqcola.Receive();
                    objOrden = (Orden)(msjmessage.Body);
                    dao.InsertarOrdenes(objOrden);
                }

                return "OK";
            }
            catch (Exception ex)
            {
                return "ERROR";
            }
        }

        public Orden ObtenerOrden(string codigo)
        {
            return dao.ObtenerOrden(codigo);
        }

        public List<Orden> ListaOrdenes()
        {
            return dao.ListarOrdenes().ToList();
        }
    }
}
